package net.oschina.simpleplus;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author ; simpleplus(simpleplus@sina.cn)
 */
public class ActionQueue {
    private ConcurrentLinkedQueue<Action> quque;
    private AtomicBoolean running;
    private ActionExecutor executor;

    public ActionQueue(ActionExecutor executor) {
        this.executor = executor;
        running = new AtomicBoolean(false);
        quque = new ConcurrentLinkedQueue<Action>();
    }


    public void checkin(Action action) {
        this.quque.offer(action);
        if(running.compareAndSet(false, true)){
            execNext();
        }
    }

    private void execNext() {
        Action next = quque.peek();
        if(next != null){
            executor.execute(next);
        }else{

            //double check
            running.set(false);
            if((next = quque.peek()) != null&& running.compareAndSet(false, true)){
                executor.execute(next);
            }
        }

        running.set(false);
    }

    public void checkinDelayedAction(DelayedAction delayedAction) {
        executor.checkinDelayedAction(delayedAction);
    }
}
